package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sms.service.OpaSmsService;
import com.budwk.app.sqfw.dto.FireHiddenPeersMsgDTO;
import com.budwk.app.sqfw.dto.SqfwFormSummaryWithFlowDTO;
import com.budwk.app.sqfw.dto.SqfwSummaryPdfExcelCollForAdminDTO;
import com.budwk.app.sqfw.enums.StreetEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormSummaryService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.SqfwSummaryForAdminService;
import com.budwk.app.sqfw.vo.HouseSurveyFormPlaceVO;
import com.budwk.app.sqfw.vo.SqfwFormSummaryUnitInfoVO;
import com.budwk.app.sqfw.vo.Sqfw_formSummaryForAdminVO;
import com.budwk.app.sqfwV2.dto.weiqingmen.OtherHiddenDangersDTO;
import com.budwk.app.sqfwV2.dto.weiqingmen.PlaceTypeDTO;
import com.budwk.app.sqfwV2.dto.weiqingmen.RectifyDTO;
import com.budwk.app.sqfwV2.dto.weiqingmen.SafetyCheckDTO;
import com.budwk.app.sqfwV2.service.weiqingmen.SafetyCheckPdfService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: SqfwWeiQMForAdminController
 * @description: 威清安全排查（后台管理系统）
 * @author: LJT
 * @create: 2023-10-11 10:20
 **/
@IocBean
@At("/platform/sqfw/forWeiQMAdmin")
@ApiDefinition(tag = "威清门管理")
@Slf4j
public class SqfwWeiQMForAdminController {

    @Inject
    private SqfwFormSummaryService sqfwFormSummaryService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private OpaSmsService opaSmsService;

    @Inject
    private SqfwSummaryForAdminService sqfwSummaryForAdminService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    private SafetyCheckPdfService safetyCheckPdfService;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "根据条件查询场所名称")
    @ApiResponses
    @SLog(tag = "根据条件查询场所信息", value = "${args[0]},${args[1]},${args[2]},${args[3]}")
    @SaCheckLogin
    public Result<?> listUnitPlaceInfo(@Param("unitId") String unitId, @Param("type") String type, @Param("unitName") String checkPlaceNameStr, @Param("returnKey") String returnKey) {
        //List<String> list = sqfwFormSummaryService.listUnitPlaceName(unitId, type, checkPlaceNameStr, returnKey);
        List<Map> list = sqfwFormSummaryService.listUnitPlaceName(unitId, type, checkPlaceNameStr, returnKey);
        return Result.success(list);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "根据场所名称获取最新场所信息")
    @ApiResponses
    @SLog(tag = "根据场所名称获取最新场所信息", value = "${args[0]},${args[1]}")
    @SaCheckLogin
    public Result<?> getUnitPlaceLatestInfo(@Param("unitName") String unitNameStr, @Param("unitId") String unitId) {
        SqfwFormSummaryUnitInfoVO vo = sqfwFormSummaryService.getUnitPlaceLatestInfo(unitNameStr, unitId);
        return Result.success(vo);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "根据场所名称获取最新场所信息")
    @ApiResponses
    @SLog(tag = "根据场所名称获取最新场所信息", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> getUnitPlaceLatestInfoById(@Param("id") String id) {
        SqfwFormSummaryUnitInfoVO vo = sqfwFormSummaryService.getUnitPlaceLatestInfoById(id);
        return Result.success(vo);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "更新表数据")
    @ApiResponses
    @SLog(tag = "更新表数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> update(@Param("..") Sqfw_formSummary sqfwFormSummary, HttpServletRequest req) {
        String userId = SecurityUtil.getUserId();
        Sys_user sysUser = sysUserService.fetch(userId);
        sqfwFormSummary.setUpdateBy(sysUser.getId());
        sqfwFormSummary.setUpdateDate(new Date());
        sqfwFormSummary.setUpdateUserName(sysUser.getUsername());
        sqfwFormSummary.setUpdateUserPhone(sysUser.getLoginname());

        sqfwFormSummaryService.updateIgnoreNull(sqfwFormSummary);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "获取详情")
    @ApiResponses
    @SLog(tag = "获取详情", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> detail(@Param("id") String id) {
        Sqfw_formSummary fetch = sqfwFormSummaryService.fetch(id);
        return Result.success(fetch);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除表数据")
    @SLog(tag = "删除表数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> delete(@Param("id") String id) {
        Sqfw_formSummary sqfwFormSummary = sqfwFormSummaryService.fetch(id);
        if (sqfwFormSummary == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwCompleteflowService.deleteAndUpdateWO(sqfwFormSummary.getSqfwFlowId());
        return Result.success();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @At("/batchDelete")
    @Ok("json")
    @POST
    @ApiOperation(name = "批量删除表数据")
    @SLog(tag = "批量删除表数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> batchDelete(@Param("ids") List<String> ids) {
        Cnd cnd = Cnd.NEW();
        cnd.and("id", "in", ids);
        List<Sqfw_formSummary> sqfwFormSummaryList = sqfwFormSummaryService.query(cnd);
        if (sqfwFormSummaryList == null || sqfwFormSummaryList.size() <= 0) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwFormSummaryList.forEach(item -> {
                    sqfwCompleteflowService.deleteAndUpdateWO(item.getSqfwFlowId());
                }
        );
        return Result.success();
    }

    @At("/generateFireHiddenPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成消防隐患排查表PDF 所有单位通用")
    @SLog(tag = "生成消防隐患排查表PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateFireHiddenPdf(@Param("..") SqfwFormSummaryWithFlowDTO formSummaryWithFlow) {
        String userId = SecurityUtil.getUserId();
        sqfwFormSummaryService.generateFireHiddenPdf(userId, formSummaryWithFlow);
        return Result.success();
    }

    @At("/retryGenerateFireHiddenPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "重新生成消防隐患排查表PDF")
    @SLog(tag = "重新生成消防隐患排查表PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> retryGenerateFireHiddenPdf(@Param("sqfwFlowId") String sqfwFlowId) {
        String userId = SecurityUtil.getUserId();
        sqfwFormSummaryService.retryGenerateFireHiddenPdf(userId, sqfwFlowId);
        return Result.success();
    }

    @At("/retryGenerateFireHiddenPdfForAdmin")
    @Ok("json")
    @GET
    @ApiOperation(name = "重新生成消防隐患排查表PDF 用于临时生成")
    @SLog(tag = "重新生成消防隐患排查表PDF 用于临时生成", value = "${args[0]}")
    public Result<?> retryGenerateFireHiddenPdfForAdmin(@Param("sqfwFlowId") String sqfwFlowId) {
        String userId = SecurityUtil.getUserId();
        sqfwFormSummaryService.retryGenerateFireHiddenPdf(userId, sqfwFlowId);
        return Result.success();
    }

    /**
     * 供小程序使用，无权限，只需要登陆即可
     *
     * @return 返回url
     */
    @At("/generateFireHiddenExcelForApp")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成消防隐患排查表Excel合集")
    @SLog(tag = "生成消防隐患排查表Excel", value = "${args[0]},${args[1]},${args[2]}")
    @SaCheckLogin
    public Result<?> generateFireHiddenCollectionExcelForApp(@Param("sqfwId") String sqfwId, @Param("workOrderId") String workOrderId, @Param("fileIndex") Integer fileIndex) {
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateFireHiddenCollectionExcelForApp("", sqfwId, workOrderId, userId, fileIndex);
        if (StringUtils.isBlank(excelUrl)) return Result.error("暂无数据，不能生成Excel");
        return Result.data(excelUrl);
    }

    @At("/sendFireHiddenPeersMsg")
    @Ok("json")
    @POST
    @ApiOperation(name = "发送同行人员短信消息")
    @SLog(tag = "发送同行人员短信消息", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> sendFireHiddenPeersMsg(@Param("..") FireHiddenPeersMsgDTO dto) {
        int sendCount = sqfwSummaryForAdminService.sendFireHiddenPeersMsg(dto);
        if (sendCount <= 0) return Result.error("发送失败");
        return Result.success();
    }

    /**
     * 供小程序使用
     *
     * @return 返回url
     */
    @At("/generateFormSummaryPdfConverge")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成Pdf合集")
    @SLog(tag = "生成Pdf合集", value = "${args[0]},${args[1]},${args[2]}")
    @SaCheckLogin
    public Result<?> generateFormSummaryPdfConverge(@Param("sqfwId") String sqfwId, @Param("workOrderId") String workOrderId, @Param("fileType") String fileType) {
        String pdfUrl = sqfwSummaryForAdminService.generateFormSummaryPdfConverge(sqfwId, workOrderId, fileType);
        if (StringUtils.isBlank(pdfUrl)) return Result.error("该任务下没有排查单");
        return Result.data(pdfUrl);
    }

    //-----------------------------------------------------------------------------------------
    //   垃圾分类调查表相关接口
    //-----------------------------------------------------------------------------------------
    @At("/generateRefuseClassifyPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成垃圾分类PDF")
    @SLog(tag = "生成垃圾分类PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateRefuseClassifyPdf(@Param("..") SqfwFormSummaryWithFlowDTO formSummaryWithFlow) {
        String userId = SecurityUtil.getUserId();
        sqfwSummaryForAdminService.generateRefuseClassifyPdf(userId, formSummaryWithFlow);
        return Result.success();
    }

    /**
     * 供小程序使用，无权限，只需要登陆即可
     *
     * @return 返回url
     */
    @At("/generateRefuseClassifyExcelForApp")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成垃圾分类排查表Excel")
    @SLog(tag = "生成垃圾分类排查表Excel", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateRefuseClassifyExcelForApp(@Param("sqfwId") String sqfwId) {
        String excelUrl = sqfwSummaryForAdminService.generateRefuseClassifyExcelForApp(sqfwId);
        if (StringUtils.isBlank(excelUrl)) return Result.error();
        return Result.data(excelUrl);
    }

    @At("/retryGenerateRefuseClassifyPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "重新生成垃圾分类排查表PDF")
    @SLog(tag = "重新生成垃圾分类排查表PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> retryGenerateRefuseClassifyPdf(@Param("sqfwFlowId") String sqfwFlowId) {
        String userId = SecurityUtil.getUserId();
        sqfwSummaryForAdminService.retryGenerateRefuseClassifyPdf(userId, sqfwFlowId);
        return Result.success();
    }

    // ----------------------------------------------------------------------------------------------
    // 生成入户调查表
    // ----------------------------------------------------------------------------------------------
    @At("/listPlaceForHouseSurveyFrom")
    @Ok("json")
    @POST
    @ApiOperation(name = "入户调查查询地点")
    @SLog(tag = "入户调查查询地点", value = "${args[0]},${args[1]},${args[2]},${args[3]}")
    @SaCheckLogin
    public Result<?> listPlaceForHouseSurveyFrom(@Param("unitId") String unitId, @Param("workOrderId") String workOrderId, @Param("a5") String a5, @Param("a4") String a4) {
        String userId = SecurityUtil.getUserId();
        List<HouseSurveyFormPlaceVO> list = sqfwSummaryForAdminService.listPlaceForHouseSurveyFrom(unitId, workOrderId, userId, a5, a4);
        return Result.success(list);
    }

    @At("/generateHouseSurveyFormPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成入户调查PDF")
    @SLog(tag = "生成垃圾分类PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateHouseSurveyFormPdf(@Param("..") SqfwFormSummaryWithFlowDTO formSummaryWithFlow) {
        String userId = SecurityUtil.getUserId();
        sqfwSummaryForAdminService.generateHouseSurveyFormPdf(userId, formSummaryWithFlow);
        return Result.success();
    }

    /**
     * 供小程序使用，无权限，只需要登陆即可
     *
     * @return 返回url
     */
    @At("/getDownloadHouseSurveyFormExcelType")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取能够生成excel的种类")
    @SLog(tag = "获取能够生成excel的种类", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> getDownloadHouseSurveyFormExcelType(@Param("sqfwId") String sqfwId) {
        List<String> excelTypeList = sqfwSummaryForAdminService.getDownloadHouseSurveyFormExcelType(sqfwId);
        return Result.data(excelTypeList);
    }

    @At("/retryGenerateHouseSurveyFormPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "重新入户调查表PDF")
    @SLog(tag = "重新入户调查表PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> retryGenerateHouseSurveyFormPdf(@Param("sqfwFlowId") String sqfwFlowId) {
        String userId = SecurityUtil.getUserId();
        sqfwSummaryForAdminService.retryGenerateHouseSurveyFormPdf(userId, sqfwFlowId);
        return Result.success();
    }

    @At("/listSecondHouseSurvey")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id需要二次入户调查的数据")
    @SLog(tag = "根据服务记录id需要二次入户调查的数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> listSecondHouseSurvey(@Param("sqfwId") String sqfwId) {
        String userId = SecurityUtil.getUserId();
        List<HouseSurveyFormPlaceVO> list = sqfwSummaryForAdminService.listSecondHouseSurvey(sqfwId, userId);
        return Result.data(list);
    }


    //--------------------------------------------------------------------------------------------
    //  根据服务记录id数组合并excel和pdf
    //--------------------------------------------------------------------------------------------
    @At("/generateServiceRecordPdfCollForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成pdf合集")
    @SLog(tag = "根据服务记录id数组生成pdf合集", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordPdfColl(@Param("conditionList") List<String> summaryIdList, @Param("fileType") String fileType, @Param("index") int index) {
        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        String pdfUrl = sqfwSummaryForAdminService.generateAppointPdfConverge(sysUser.getId(), summaryIdList, fileType, index);
        if (ResultCode.NULL_DATA_ERROR.getMsg().equals(pdfUrl)) {
            return Result.error(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        return Result.data(pdfUrl);
    }

    @At("/generateServiceRecordExcelColl")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成Excel合集")
    @SLog(tag = "根据服务记录id数组生成Excel合集", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelColl(@Param("conditionList") List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList, @Param("fileIndex") Integer fileIndex, @Param("excelType") String excelType) {
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateCheckRecordExcelColl("", conditionList, userId, fileIndex, excelType);
        return Result.data(excelUrl);
    }

    /**
     * 后台管理系统任务列表查询（用于后台管理系统）
     * Add by LJT 2023-10-10
     */
    @At("/listSummaryForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "后台管理系统任务列表查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @ApiResponses(
            implementation = Sqfw_formSummary.class
    )
    @SLog(tag = "后台管理系统任务列表查询", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> listSummaryForBM(@Param("..") Sqfw_formSummaryForAdminVO bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        return sqfwSummaryForAdminService.listSummaryWQMForBM(bean, pageNo, pageSize, pageOrderName, pageOrderBy);
    }

    /**
     * 勾选下载，后台管理系统任务下载excel集合（用于后台管理系统）
     * Add by LJT 2023-10-10
     */
    @At("/generateServiceRecordExcelCollForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id和汇总Id数组生成Excel合集")
    @SLog(tag = "根据服务记录id数组和汇总Id生成Excel合集", value = "${args[0]},${args[1]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelCollForBM(
            @Param("sumIdList") List<String> sumIdList,
            @Param("fileIndex") Integer fileIndex) {
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateServiceRecordExcelCollForBM("", sumIdList, userId, "", fileIndex);
        return Result.data(excelUrl);
    }

    /**
     * 后台管理系统任务下载excel集合压缩包（用于后台管理系统）
     * Add by LJT 2023-10-17
     */
    @At("/generateServiceRecordExcelCollZipForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id和汇总Id数组生成Excel合集")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @SLog(tag = "根据服务记录id数组和汇总Id生成Excel合集", value = "${args[0]},${args[1]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelCollZipForBM(@Param("..") Sqfw_formSummaryForAdminVO bean, @Param("fileIndexList") List<Integer> fileIndexList) {
        List<String> sumIdList = sqfwSummaryForAdminService.getWeiQingMenExcelFileDownSumIdList(bean);
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateServiceSummaryExcelCollZipForBM("", bean.getCounty(), sumIdList, userId, fileIndexList, "", bean.getQueryTime());
        if(StringUtils.isNotEmpty(excelUrl) && excelUrl.contains("https://xyoss.obs.cn-hcsoysgz1.hcsoysgz.gzdata.com.cn")) {
            excelUrl = excelUrl.replace("https://xyoss.obs.cn-hcsoysgz1.hcsoysgz.gzdata.com.cn:443", "https://f.xyasst.com/myhuaweicloud/");
        }
        return Result.data(excelUrl);
    }

    /**
     * 根据 index 下载模板
     *
     * @return
     * @Date 2023-11-23
     */
    @At("/downloadTemplateForIndex")
    @Ok("json")
    @POST
    @ApiOperation(name = "模板下载")
    @SLog(tag = "模板下载", value = "")
    @ApiFormParams({@ApiFormParam(name = "sqfwId", description = "服务ID"), @ApiFormParam(name = "excelType", description = "EXCEL类型")})
    @SaCheckLogin
    public Result<?> downloadTemplateForIndex( @Param("fileIndex") Integer fileIndex, @NotNull @Param("isWord") String isWord) {
        return Result.data(sqfwFormSummaryService.downloadTemplateForIndex(fileIndex,  isWord, StreetEnum.WEI_QING_MEN_STREET.getName()));
    }


    /**
     * 数据检测
     * Add by LJT 2023-10-17
     */
    @At("/checkDataForQuery")
    @Ok("json")
    @POST
    @ApiOperation(name = "数据检测")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @SLog(tag = "数据检测", value = "${args[0]},${args[1]}")
    @SaCheckLogin
    public Result<?> checkDataForQuery(@Param("..") Sqfw_formSummaryForAdminVO bean, @Param("fileIndexList") List<Integer> fileIndexList) {
        return Result.data(sqfwSummaryForAdminService.checkDataForQuery(bean));
    }

    /**
     * 数据检测
     * Add by LJT 2023-10-17
     */
    @At("/checkDataForIds")
    @Ok("json")
    @POST
    @ApiOperation(name = "数据检测")
    @SLog(tag = "数据检测", value = "${args[0]},${args[1]}")
    @SaCheckLogin
    public Result<?> checkDataForIds(@Param("ids") List<String> ids) {
        return Result.data(sqfwSummaryForAdminService.checkDataForIds(ids));
    }

    /**
     * 后台管理系统任务下载pdf集合压缩包（用于后台管理系统）
     * Add by LJT 2023-10-17
     */
    @At("/generateServiceRecordPdfCollZipForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成pdf合集zip")
    @ApiFormParams(
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @SLog(tag = "根据服务记录id数组生成pdf合集zip", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordPdfCollZipForBM(@Param("..") Sqfw_formSummaryForAdminVO bean, @Param("fileType") String fileType, @Param("index") int index) {
        List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList = sqfwSummaryForAdminService.getWeiQingmenPdfFileDownSumIdList(bean);
        List<String> summaryIdList = conditionList.stream().map(SqfwSummaryPdfExcelCollForAdminDTO::getSumId).collect(Collectors.toList());
        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        String pdfUrl = sqfwSummaryForAdminService.generateAppointPdfConverge(sysUser.getId(), summaryIdList, fileType, index);
        if (ResultCode.NULL_DATA_ERROR.getMsg().equals(pdfUrl)) {
            return Result.error(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        return Result.data(pdfUrl);
    }


//    /**
//     * 威清门重新对a37和a64内容进行更新
//     * @return
//     */
//    @At("/dataRepair")
//    @Ok("json")
//    @GET
//    @ApiOperation(name = "数据修复")
//    public Result<?> dataRepair() {
//        String sql = "select a1,community,max(fill_date)fill_date from shequ.sqfw_form_summary where " +
//                "county  ='威清门街道' and type='安全排查' group by a1,community";
//        List<Sqfw_formSummary> formSummaryList = sqfwFormSummaryService.listEntity(Sqls.create(sql));
//        for (Sqfw_formSummary formSummary : formSummaryList) {
//            //获取上一次的巡查
//            Cnd cnd = Cnd.NEW();
//            cnd.and("county", "=", "威清门街道")
//                    .and("a1", "=", formSummary.getA1())
//                    .and("community", "=", formSummary.getCommunity())
//                    .and("fill_date", "<", formSummary.getFillDate());
//            cnd.orderBy("fill_date", "desc");
//            Sqfw_formSummary fUp = sqfwFormSummaryService.fetch(cnd);
//
//            //获取最新的巡查
//            Cnd c = Cnd.NEW();
//            c.and("county", "=", "威清门街道")
//                    .and("a1", "=", formSummary.getA1())
//                    .and("community", "=", formSummary.getCommunity())
//                    .and("fill_date", "=", formSummary.getFillDate());
//            Sqfw_formSummary f = sqfwFormSummaryService.fetch(c);
//
//            if (fUp != null) {
//                String a7_up = fUp.getA7();
//                String a42_up = fUp.getA42();
//                String a7 = f.getA7();
//                String a41 = f.getA41();
//                String a42 = f.getA42();
//                if ("有".equals(a7_up) && "无".equals(a7)) {
//                    f.setA64("已整改");
//                } else if ("有".equals(a7)) {
//                    f.setA64("未整改");
//                } else {
//                    f.setA64("正常");
//                }
//                if (getSize(a42) > 0 || "未整改".equals(f.getA64())) {
//                    f.setA37("未整改");
//                } else if (getSize(a41) > 0 || (getSize(a42_up) > 0 && getSize(a41) == 0) || "已整改".equals(f.getA64())) {
//                    f.setA37("已整改");
//                } else {
//                    f.setA37("正常");
//                }
//            } else {
//                String a7 = f.getA7();
//                String a41 = f.getA41();
//                String a42 = f.getA42();
//
//                if ("有".equals(a7)) {
//                    f.setA64("未整改");
//                } else {
//                    f.setA64("正常");
//                }
//
//                if (getSize(a42) > 0 || "未整改".equals(f.getA64())) {
//                    f.setA37("未整改");
//                } else if (getSize(a41) > 0 || "已整改".equals(f.getA64())) {
//                    f.setA37("已整改");
//                } else {
//                    f.setA37("正常");
//                }
//            }
//            Sqfw_formSummary sf = new Sqfw_formSummary();
//            sf.setId(f.getId());
//            sf.setA37(f.getA37());
//            sf.setA64(f.getA64());
//            sqfwFormSummaryService.updateIgnoreNull(sf);
//        }
//        return Result.data("ok");
//    }
//
//    private int getSize(String str) {
//        if (StringUtils.isBlank(str)) return 0;
//        if (str.contains("[")) {
//            JSONArray jsonArray = JSON.parseArray(str);
//            return jsonArray.getJSONArray(0).size() + jsonArray.getJSONArray(1).size() + jsonArray.getJSONArray(2).size();
//        }
//        return 0;
//    }

    /**
     * 威清门重重构数据清洗
     * @return
     */
    @At("/dataCleanse")
    @Ok("json")
    @GET
    @SaCheckLogin
    public Result<?> dataCleanse(@Param("isWashData") boolean isWashData) {
        dataCleanse(0, isWashData);
        return Result.data("ok");
    }

    private void dataCleanse(int page, boolean isWashData) {
        String sql = "select * from shequ.sqfw_form_summary where county  ='威清门街道' and type='安全排查' order by create_date desc LIMIT 100 OFFSET " + page;
        List<Sqfw_formSummary> formSummaryList = sqfwFormSummaryService.listEntity(Sqls.create(sql));
        for (Sqfw_formSummary formSummary : formSummaryList) {
            System.out.println("老数据："+JSON.toJSONString(formSummary));
            try {
                Sqfw_formSummary_new formSummaryNew = new Sqfw_formSummary_new();
                BeanUtil.copyProperties(formSummary, formSummaryNew);
                String s = formSummary.getIssueStatus();
                formSummaryNew.setIssueStatus("正常".equals(s)?"0":"现场".equals(s)?"1":"2");
                SafetyCheckDTO safetyCheckDTO = new SafetyCheckDTO();
                safetyCheckDTO.setPlaceName(formSummary.getA1());
                safetyCheckDTO.setAddress(formSummary.getA2());
                safetyCheckDTO.setOperator(formSummary.getA3());
                safetyCheckDTO.setOperatorTelephone(formSummary.getA4());
                safetyCheckDTO.setHaveABusinessLicense(StringUtils.isBlank(formSummary.getA5())?true:"有".equals(formSummary.getA5()));
                PlaceTypeDTO placeType = new PlaceTypeDTO();
                placeType.setKey(formSummary.getA6());
                safetyCheckDTO.setPlaceType(placeType);
                RectifyDTO thereAreNoViolationsToLive = new RectifyDTO();
                if ("无".equals(formSummary.getA7())) {
                    thereAreNoViolationsToLive.setKey(false);
                } else {
                    thereAreNoViolationsToLive.setKey(true);
                }
                safetyCheckDTO.setThereAreNoViolationsToLive(thereAreNoViolationsToLive);
                safetyCheckDTO.setThereAreNoInflammableMaterials(StringUtils.isBlank(formSummary.getA8())?true:"有".equals(formSummary.getA8()));
                safetyCheckDTO.setIsPeriodicalAirAndPersonTrain(StringUtils.isBlank(formSummary.getA9())?true:"有".equals(formSummary.getA9()));
                safetyCheckDTO.setFireFightingEquipment(formSummary.getA10());
                safetyCheckDTO.setByFiregas(formSummary.getA11());
                safetyCheckDTO.setByFireelectricity(formSummary.getA12());
                safetyCheckDTO.setCheckYourWorkRecords(formSummary.getA13());
                safetyCheckDTO.setTechnicalDefenseFacilities(formSummary.getA14());
                safetyCheckDTO.setBuildingStructure(formSummary.getA15());
                safetyCheckDTO.setPlaceFireExtinguishersNumber(formSummary.getA16());
                safetyCheckDTO.setFireAndElectricityUsage(formSummary.getA17());
                safetyCheckDTO.setInspectionPhotos(formSummary.getA18());
                safetyCheckDTO.setPeers(formSummary.getA19());
                safetyCheckDTO.setCheckedUnitLeader(formSummary.getA20());
                safetyCheckDTO.setDoesSupplyCarry(StringUtils.isBlank(formSummary.getA23())?true:"是".equals(formSummary.getA23()));
                safetyCheckDTO.setGasCylinderStorageAreaAfterMarketClose(formSummary.getA25());
                safetyCheckDTO.setLiquefiedGasUsage(formSummary.getA26());
                safetyCheckDTO.setLiquefiedGasNumber(formSummary.getA27());
                safetyCheckDTO.setGasDeliveryCompany(formSummary.getA28());
                safetyCheckDTO.setIsGasStorageCompliant(StringUtils.isBlank(formSummary.getA29())?true:"是".equals(formSummary.getA29()));
                safetyCheckDTO.setWeakLine(formSummary.getA45());
                safetyCheckDTO.setHighCurrentLine(formSummary.getA46());
                safetyCheckDTO.setEmergencySafetyHazard(formSummary.getA47());
                safetyCheckDTO.setPlaceArea(formSummary.getA48());
                safetyCheckDTO.setIsThereDutyRoom(StringUtils.isBlank(formSummary.getA50())?true:"是".equals(formSummary.getA50()));
                safetyCheckDTO.setIsHaveMicroFireStations(StringUtils.isBlank(formSummary.getA51())?true:"是".equals(formSummary.getA51()));
                safetyCheckDTO.setPublicSecurityFireExaminationAndApproval(StringUtils.isBlank(formSummary.getA52())?true:"是".equals(formSummary.getA52()));
                safetyCheckDTO.setNumberOfRooms(formSummary.getA53());
                safetyCheckDTO.setNumberOfBed(formSummary.getA54());
                safetyCheckDTO.setNumberOfAdministrativeBuildings(formSummary.getA55());
                safetyCheckDTO.setBuildingHeight(formSummary.getA56());
                safetyCheckDTO.setCarryOutConstructionWorkSafely(StringUtils.isBlank(formSummary.getA57())?true:"有".equals(formSummary.getA57()));
                safetyCheckDTO.setPersonnelRelatedQualificationCertificate(StringUtils.isBlank(formSummary.getA58())?true:"有".equals(formSummary.getA58()));
                safetyCheckDTO.setSafetyOfficerOrNot(StringUtils.isBlank(formSummary.getA59())?true:"有".equals(formSummary.getA59()));
                safetyCheckDTO.setEmergencyMeasure(formSummary.getA60());
                safetyCheckDTO.setWhetherItIsThreeInOne(StringUtils.isBlank(formSummary.getThreeInOne())?true:"是".equals(formSummary.getThreeInOne()));
                safetyCheckDTO.setThreeInOnePhoto(formSummary.getThreeInOneImg());
                safetyCheckDTO.setWhetherItIsATrafficEmergency(StringUtils.isBlank(formSummary.getIsTrafficEmergency())?true:
                        "是".equals(formSummary.getIsTrafficEmergency()));
                try {
                    safetyCheckDTO.setDeadlineForRectification(StringUtils.isBlank(formSummary.getA30()) ? null : DateUtil.parse(formSummary.getA30(), DatePattern.CHINESE_DATE_PATTERN));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                safetyCheckDTO.setAttributesOfInspectionUnits(formSummary.getA61());
                safetyCheckDTO.setInspectionDate(formSummary.getFillDate());

                JSONArray jsonArray = JSON.parseArray(formSummary.getA38());
                if (jsonArray != null) {
                    // 限期
                    JSONArray a38_0 = jsonArray.getJSONArray(0);// 消防
                    JSONArray a38_1 = jsonArray.getJSONArray(1);// 瓶装一般
                    JSONArray a38_2 = jsonArray.getJSONArray(2);// 瓶装重大

                    JSONArray a38_3 = new JSONArray();
                    JSONArray a38_4 = new JSONArray();
                    JSONArray a38_5 = new JSONArray();
                    // 现场
                    if (jsonArray.size() > 3) {
                        a38_3 = jsonArray.getJSONArray(3);// 消防
                        a38_4 = jsonArray.getJSONArray(4);// 瓶装一般
                        a38_5 = jsonArray.getJSONArray(5);// 瓶装重大
                    }

                    //消防安全问题
                    String val1 = "[{\"title\":\"在地下或半地下空间、高层建筑内使用瓶装燃气。\"},{\"title\":\"存放气瓶总重量超过100kg未设置专用气瓶间。\"},{\"title\":\"在用气瓶和备用气瓶未分开放置。\"},{\"title\":\"燃气连接软管长度超过2米。\"},{\"title\":\"橡胶软管私接“三通或连接软管穿越墙体、门窗、顶棚地面。\"},{\"title\":\"使用两种以上“火源”。\"},{\"title\":\"未规范安装、使用燃气泄漏报警装置及燃气紧急切断阀。\"},{\"title\":\"违规存储、使用工业醇基燃料、瓶装液化燃气。\"},{\"title\":\"电动自行车室内停放、充电。\"},{\"title\":\"电气线路敷设在易燃、可燃材料上。\"},{\"title\":\"安全出口堵塞、锁闭。\"},{\"title\":\"疏散通道、楼梯间堆放杂物。\"},{\"title\":\"外窗违规设置防盗网或铁栅栏。\"},{\"title\":\"未配备灭火器。\"},{\"title\":\"经营者或员工不会组织卦数初起火灾或不会组织疏散逃生。\"}]";
                    JSONArray safetyArray = JSON.parseArray(val1);
                    for (int i = 0; i < a38_0.size(); i++) {
                        String v = a38_0.getString(i);
                        if (StringUtils.isBlank(v) || v.indexOf(".") == -1) continue;
                        int k = Integer.parseInt(v.substring(0, v.indexOf("."))) - 1;
                        safetyArray.getJSONObject(k).put("rectificationDate", "限期整改");
                        safetyArray.getJSONObject(k).put("hiddenType", "一般");
                    }
                    for (int i = 0; i < a38_3.size(); i++) {
                        String v = a38_3.getString(i);
                        if (StringUtils.isBlank(v) || v.indexOf(".") == -1) continue;
                        int k = Integer.parseInt(v.substring(0, v.indexOf("."))) - 1;
                        safetyArray.getJSONObject(k).put("rectificationDate", "现场整改");
                        safetyArray.getJSONObject(k).put("hiddenType", "一般");
                    }

                    List<RectifyDTO> arrayOfFireSafetyPatrolRecords = JSON.parseArray(safetyArray.toJSONString(), RectifyDTO.class);
                    safetyCheckDTO.setArrayOfFireSafetyPatrolRecords(arrayOfFireSafetyPatrolRecords);

                    // 瓶装液化气问题
                    //【瓶装燃气用户安全管理检查表】每个问题分别对应有风险类型（只有瓶装燃气才有重大问题）：
                    //一般隐患有：问题1，2，3，5，6，7，10，13，21，22，24，25，26，27。
                    //重大隐患有：问题4，8，9，11，12，14，15，16，17，18，19，20，23。
                    String val2 = "[{\"title\":\"非居民用户应制定安全管理制度、应急处置流程。\"},{\"title\":\"非居民用户应定期开展燃气设施安全检查，形成检查记录。\"},{\"title\":\"操作人员应掌握燃气的基本知识、泄漏判断及检查方法、掌握应急处置措施。\"},{\"title\":\"居民用户选用液化石油气或城镇燃气用二甲醚专用燃具，燃具应设置熄火保护装置。应当使用合格的燃烧器具，燃气燃烧器具不超过判废年限。\"},{\"title\":\"与燃具贴邻的墙体、地面、台面等，应为不燃材料。燃具与可燃或难燃的墙壁、地板、家具之间应保持足够的间距或采取其他有效的防护措施。\"},{\"title\":\"不得在燃气设施上缠绕电线、悬挂其他物品。\"},{\"title\":\"非居民用户燃具或用气设备应设置在通风良好、符合安全使用条件且便于维护操作的场所。\"},{\"title\":\"非居民用户燃具或用气设备应设置在通风良好、符合安全使用条件且便于维护操作的场所。禁止在密闭空间和人员居住休息的房间、卫生间内储存及使用瓶装燃气；禁止在地下室、半地下室或高层建筑物内使用瓶装燃气。\"},{\"title\":\"燃气使用场所禁止使用其他燃料，禁止存放其他易燃易爆物品。\"},{\"title\":\"非居用户应按规定配备灭火器等消防器材。\"},{\"title\":\"气瓶专属存放场所应通风良好，不得有裸露电线，不得使用非防爆电气设备，不得存放在地下室及半地下室。禁止存放其他易燃物品。\"},{\"title\":\"商业燃气用户气瓶使用场所不得超量存放（如 YSP118 型的重瓶存量不得超过 2 瓶，YSP35.5 型的重瓶存量不得超过 7 瓶）；存瓶总重量超过 100 公斤（YSP118 型的重瓶 2 瓶以上或 YSP35.5 型的重瓶 7 瓶以上），需设置独立瓶组间；存瓶总重量超过 100 千克小于 420 千克时，气瓶间可以设置在与用气建筑相邻的单层专用房间内；存瓶总重量大于 420 千克时，气瓶间应当为与其他民用建筑间距不小于 10 米的独立建筑。\"},{\"title\":\"可燃气体泄漏报警装置、紧急切断阀的安装符合《城镇燃气报警器控制系统技术规程》(CJJ146)规范要求。\"},{\"title\":\"餐饮经营场所、学校、医院、农贸市场等人员密集场所内生产经营单位使用燃气的，必须安装合格的可燃气体泄漏报警和紧急切断装置，必须能正常使用，有检查记录，不得超期使用。\"},{\"title\":\"有独立瓶组存放间；禁止设置于地下室或半地下室；设置有效的燃气泄漏报警装置；不得存放杂物或其他易燃物品；不得使用非防爆的电气设备；独立瓶组间应满足与建筑的防火间距要求。\"},{\"title\":\"瓶组与气化器禁止同处一室。\"},{\"title\":\"禁止用热水、火源或其他热源对气瓶加热；禁止横置、倾倒使用气瓶。\"},{\"title\":\"禁止在有燃气设施设备的房间内住人；禁止使用电梯运输瓶装燃气。\"},{\"title\":\"禁止在燃气设施上缠绕电线、悬挂其他物品。\"},{\"title\":\"使用场所不存在第二气源（火源）。\"},{\"title\":\"与燃具采用软管连接时，应采用专用燃具连接软管（不锈钢波纹软管、复合橡胶软管等）。\"},{\"title\":\"软管的使用年限不应低于燃具的判废年限。\"},{\"title\":\"橡胶软管中间禁止有接口，禁止有三通，应穿越墙体、门窗、顶棚和地面等。\"},{\"title\":\"橡胶软管连接部位应安装管卡。\"},{\"title\":\"燃气管线系统应由相关资质的设计、施工单位负责实施；管道材质符合规范要求。\"},{\"title\":\"调压器符合国家规范《瓶装液化石油气调压器》（GB35844）相关要求，调压器无腐蚀，密封圈无老化、无泄漏；调压器输出压力与燃气燃烧器具的额定压力相匹配。\"},{\"title\":\"禁止使用可调节的液化石油气调压器。\"}]";
                    JSONArray bottledArray = JSON.parseArray(val2);
                    for (int i = 0; i < a38_1.size(); i++) {
                        String v = a38_1.getString(i);
                        if (StringUtils.isBlank(v) || v.indexOf(".") == -1) continue;
                        int k = Integer.parseInt(v.substring(0, v.indexOf("."))) - 1;
                        bottledArray.getJSONObject(k).put("rectificationDate", "限期整改");
                        bottledArray.getJSONObject(k).put("hiddenType", "一般");
                    }
                    for (int i = 0; i < a38_2.size(); i++) {
                        String v = a38_2.getString(i);
                        if (StringUtils.isBlank(v) || v.indexOf(".") == -1) continue;
                        int k = Integer.parseInt(v.substring(0, v.indexOf("."))) - 1;
                        bottledArray.getJSONObject(k).put("rectificationDate", "限期整改");
                        bottledArray.getJSONObject(k).put("hiddenType", "重大");
                    }
                    for (int i = 0; i < a38_4.size(); i++) {
                        String v = a38_4.getString(i);
                        if (StringUtils.isBlank(v) || v.indexOf(".") == -1) continue;
                        int k = Integer.parseInt(v.substring(0, v.indexOf("."))) - 1;
                        bottledArray.getJSONObject(k).put("rectificationDate", "现场整改");
                        bottledArray.getJSONObject(k).put("hiddenType", "一般");
                    }
                    for (int i = 0; i < a38_5.size(); i++) {
                        String v = a38_5.getString(i);
                        if (StringUtils.isBlank(v) || v.indexOf(".") == -1) continue;
                        int k = Integer.parseInt(v.substring(0, v.indexOf("."))) - 1;
                        bottledArray.getJSONObject(k).put("rectificationDate", "现场整改");
                        bottledArray.getJSONObject(k).put("hiddenType", "重大");
                    }

                    List<RectifyDTO> bottledGasProblemArray = JSON.parseArray(bottledArray.toJSONString(), RectifyDTO.class);
                    safetyCheckDTO.setBottledGasProblemArray(bottledGasProblemArray);
                }

                // 其他问题
                String other = formSummary.getA31();
                OtherHiddenDangersDTO otherHiddenDangers = new OtherHiddenDangersDTO();
                otherHiddenDangers.setKey(other);
                safetyCheckDTO.setOtherHiddenDangers(otherHiddenDangers);

                // 图片
                if (StringUtils.isNotBlank(formSummary.getA43())) {
                    RectifyDTO oldImg = new RectifyDTO();
                    //因为老数据的a43不是数组，所以要在此判断
                    boolean isArray = true;
                    JSONArray a43 = null;
                    try {
                        a43 = JSON.parseArray(formSummary.getA43());
                    } catch (Exception e) {
                        isArray = false;
                    }

                    //整改前
                    String before_picture = isArray ? a43.getString(0) : formSummary.getA43();
                    //整改后
                    String after_picture = isArray ? a43.getString(1) : formSummary.getA43();
                    oldImg.setPicturesBeforeRectification(before_picture);
                    oldImg.setPicturesAfterRectification(after_picture);
                    safetyCheckDTO.setOldImg(oldImg);

                    // 危房图片
                    String morning = null;
                    String noon = null;
                    String night = null;
                    try {
                        morning = isArray ? a43.getString(2) : formSummary.getA43();
                        noon = isArray ? a43.getString(3) : formSummary.getA43();
                        night = isArray ? a43.getString(4) : formSummary.getA43();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    safetyCheckDTO.setDilapidatedHousePhotoEarly(morning);
                    safetyCheckDTO.setDilapidatedHouseInPhoto(noon);
                    safetyCheckDTO.setDangerousHousePhotoLate(night);
                }

                formSummaryNew.setParamData(JSON.toJSONString(safetyCheckDTO));

                System.out.println("新数据：" + JSON.toJSONString(formSummaryNew));

                // 是否清洗数据
                if (isWashData) {
                    Cnd cnd = Cnd.NEW();
                    cnd.and(Sqfw_formSummary_new::getId, "=", formSummaryNew.getId());
                    List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.query("id", cnd);
                    if (formSummaryNewList.size() > 0) {
                        sqfwFormsummaryNewService.update(formSummaryNew);
                    } else {
                        sqfwFormsummaryNewService.insert(formSummaryNew);
                    }
                }
                // 重置pdf
                safetyCheckPdfService.reCreatePdfAndMsg(formSummaryNew.getSqfwFlowId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (formSummaryList.size() == 100) {
            page += 100;
            dataCleanse(page, isWashData);
        }
    }
}
